﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using EARTHLib;
using System.Drawing;

namespace PolePosition.v3.GoogleEarth
{
    class MapHelper
    {
        #region WIN API

        public delegate int EnumWindowsProc(IntPtr hwnd, int lParam);
        [DllImport("user32", CharSet = CharSet.Auto)]
        public extern static IntPtr GetParent(IntPtr hWnd);

        [DllImport("user32", CharSet = CharSet.Auto)]
        public extern static bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

        [DllImport("user32", CharSet = CharSet.Auto)]
        public extern static IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        [DllImport("User32.Dll")]
        public static extern IntPtr PostMessage(IntPtr hWnd, int msg, int wParam, int lParam);

        private const int WM_CLOSE = 0x10;

        #endregion WIN API

        #region VARIABLES

        protected bool _CloseGE = false;
        protected double _ZoomLevel = 10000000;
        public double ZoomLevel
        {
            get
            {
                return _ZoomLevel;
            }
            set
            {
                _ZoomLevel = value;
            }
        }

        private static IntPtr GEHrender = (IntPtr)0;
        private static IntPtr GEParentHrender = (IntPtr)0;
        private static IntPtr GEMainHrender = (IntPtr)0;
        public ApplicationGEClass m_GoogleEarth;
        private static Point m_ClickedMousePosition;
        private static Point m_ScreenOrigin;

        #endregion VARIABLES    

        public MapPosition GetCurrentCoordinates(ApplicationGEClass googleEarth, double width, double height)
        {
            Point _PositionClickedInGE;
            _PositionClickedInGE = new Point();
            _PositionClickedInGE.X = m_ClickedMousePosition.X - m_ScreenOrigin.X;
            _PositionClickedInGE.Y = m_ClickedMousePosition.Y - m_ScreenOrigin.Y;

            double _PercentageWidth;
            _PercentageWidth = ((2 * ((double)_PositionClickedInGE.X / width)) - 1);
            
            double _PercentageHeight;
            _PercentageHeight = -1 * ((2 * ((double)_PositionClickedInGE.Y / height) - 1));

            PointOnTerrainGE _PointOnTerrainGE;
            _PointOnTerrainGE = new PointOnTerrainGE();
            _PointOnTerrainGE = m_GoogleEarth.GetPointOnTerrainFromScreenCoords(_PercentageWidth, _PercentageHeight);

            MapPosition _CurrentPosition = new MapPosition();
            _CurrentPosition.Altitude = _PointOnTerrainGE.Altitude;
            _CurrentPosition.Latitude = _PointOnTerrainGE.Latitude;
            _CurrentPosition.Longitude = _PointOnTerrainGE.Longitude;
            return _CurrentPosition;
        }
    }
}
